<template>
  <div class="page-title">
    <p class="con-title">
      <span>
        <img src="@/assets/img/control/content/Group769.png" />
      </span>
      <span>安全组规则配置</span>
    </p>
    <el-button type="primary" plain @click="goback">返回</el-button>
  </div>

  <el-tabs v-model="safeType" @tab-click="chooseType">
    <el-tab-pane label="入方向规则" name="ingress" />
    <el-tab-pane label="出方向规则" name="egress" />
  </el-tabs>
  <el-button type="primary" plain @click="addRules">添加</el-button>

  <!-- 配置规则表格 -->
  <el-table :data="safeRulesListPage" header-cell-class-name="title-style" border class="table">
    <!-- <el-table-column prop="priority" label="优先级" align="center">
      <template #default="scope">
        <el-input v-if="scope.row.isEdit" v-model="scope.row.priority" type="text" placeholder="请输入优先级1-100" />
        <div v-else>{{ scope.row.priority }}</div>
      </template>
    </el-table-column>

    <el-table-column prop="action" label="策略" align="center">
      <template #default="scope">
        <el-select v-if="scope.row.isEdit" v-model="scope.row.action" placeholder="请选择策略">
          <el-option label="允许" value="allow " />
          <el-option label="拒绝" value="deny " />
        </el-select>
        <div v-else>{{ scope.row.action == 'allow' ? '允许' : scope.row.action == 'deny' ? '拒绝' : '' }}</div>
      </template>
    </el-table-column> -->

    <el-table-column prop="ethertype" label="类型" align="center">
      <template #default="scope">
        <el-select v-if="scope.row.isEdit" v-model="scope.row.ethertype" placeholder="请选择类型">
          <el-option label="IPv4" value="IPv4" />
          <el-option label="IPv6" value="IPv6" />
        </el-select>
        <div v-else>{{ scope.row.ethertype }}</div>
      </template>
    </el-table-column>

    <el-table-column prop="direction" label="规则方向" align="center">
      <template #default="scope">
        <span v-if="scope.row.direction == 'egress'">出方向规则</span>
        <span v-if="scope.row.direction == 'ingress'">入方向规则</span>
      </template>
    </el-table-column>

    <el-table-column prop="protocol,multiport" label="协议端口" align="center">
      <template #default="scope">
        <div v-if="scope.row.isEdit">
          <el-cascader v-model="scope.row.protocol" :options="protocolOptions" @change="ethertypeChange" />
          <el-input v-model="scope.row.multiport" type="text" placeholder="请输入端口值1~65535" style="margin-top:10px" />
        </div>
        <div v-else>
          {{ scope.row.protocol ? `${scope.row.protocol?.toUpperCase()}${scope.row.multiport ? ':' + scope.row.multiport :
            ''
            }` : '全部' }}
        </div>
      </template>
    </el-table-column>

    <el-table-column prop="remote_ip_prefix" label="源地址" align="center">
      <template #default="scope">
        <div v-if="scope.row.isEdit">
          <el-select v-model="scope.row.Ipdizhi" placeholder="请选择类型">
            <el-option label="IP地址" value="IP地址" />
            <el-option label="安全组" value="安全组" />
            <el-option label="IP地址组" value="IP地址组" />
          </el-select>
          <el-input v-model="scope.row.remote_ip_prefix" type="text" placeholder="请输入" style="margin-top:10px" />
        </div>
        <div v-else>{{ scope.row.remote_ip_prefix }}</div>
      </template>
    </el-table-column>

    <el-table-column prop="description" label="描述" align="center" show-overflow-tooltip>
      <template #default="scope">
        <div v-if="scope.row.isEdit">
          <el-input v-model="scope.row.description" type="text" placeholder="请输入" />
        </div>
        <div v-else>{{ scope.row.description }}</div>
      </template>
    </el-table-column>
    <el-table-column prop="updated_at" label="修改时间" align="center" />
    <el-table-column label="操作" width="150" align="center">
      <template #default="scope">
        <div v-if="scope.row.isEdit == 'false' || !scope.row.isEdit">
          <!-- <el-button type="primary" link @click="doUpdate(scope.row)">修改</el-button> -->
          <!-- <el-button type="danger" link @click="pasteOneTable(scope.row, scope.$index)">复制</el-button> -->
          <el-button type="danger" link @click="delOneTable(scope.row)">删除</el-button>
        </div>
        <div v-if="scope.row.isEdit">
          <el-button type="primary" link @click="sureUpdate(scope.row)">确认</el-button>
          <el-button type="primary" link @click="cancelUpdate(scope.row)">取消</el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加修改对话框 -->
  <el-dialog v-model="isRules" title="添加" width="90vw">
    <el-table :data="addRulesList" header-cell-class-name="title-style" border class="table">
      <el-table-column prop="priority" label="优先级" align="center">
        <template #default="scope">
          <el-input v-model="scope.row.priority" type="text" placeholder="请输入优先级1-100" />
        </template>
      </el-table-column>

      <el-table-column prop="" label="策略" align="center">
        <template #default="scope">
          <el-select v-model="scope.row.action" placeholder="请选择策略">
            <el-option label="允许" value="allow" />
            <el-option label="拒绝" value="deny" />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column prop="ethertype" label="类型" align="center">
        <template #default="scope">
          <el-select v-model="scope.row.ethertype" placeholder="请选择类型">
            <el-option label="IPv4" value="IPv4" />
            <el-option label="IPv6" value="IPv6" />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column prop="direction" label="规则方向" align="center">
        <template #default="scope">
          <el-select v-model="scope.row.direction" placeholder="请选择类型">
            <el-option label="出方向规则" value="egress" />
            <el-option label="入方向规则" value="ingress" />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column prop="protocol,multiport" label="协议端口" align="center">
        <template #default="scope">
          <el-cascader v-model="protocolType" :options="protocolOptions"
            @change="ethertypeChange($event, scope.$index)" />
          <el-input v-model="scope.row.multiport" type="text" placeholder="例如:22或22,24或22-30" style="margin-top:10px"
            :disabled="isAll" />
        </template>
      </el-table-column>

      <el-table-column prop="remote_ip_prefix" label="源地址" align="center">
        <template #default="scope">
          <el-select v-model="scope.row.Ipdizhi" placeholder="请选择类型" @change="getIPType($event, scope.$index)">
            <el-option label="IP地址" value="IP地址" />
            <el-option label="安全组" value="安全组" />
            <el-option label="IP地址组" value="IP地址组" />
          </el-select>
          <el-input v-show="typeShow === '安全组'" v-model="scope.row.remote_group_id" type="text" placeholder="请输入"
            style="margin-top:10px" />
          <el-input v-show="typeShow === 'IP地址'" v-model="scope.row.remote_ip_prefix" type="text" placeholder="请输入"
            style="margin-top:10px" />
          <el-input v-show="typeShow === 'IP地址组'" v-model="scope.row.remote_address_group_id" type="text"
            placeholder="请输入" style="margin-top:10px" />
        </template>
      </el-table-column>

      <el-table-column prop="description" label="描述" align="center">
        <template #default="scope">
          <el-input v-model="scope.row.description" type="text" placeholder="请输入" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="pasteOne(scope.row, scope.$index)">复制</el-button>
          <el-button type="primary" link :disabled="addRulesList.length <= 1"
            @click="delOne(scope.row, scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="addbtn">
      <el-button link :icon="CirclePlus" @click="addRulesOne">增加1条规则</el-button>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelAdd()">取消</el-button>
        <el-button type="primary" @click="sureAdd()">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
    :small="false" :disabled="false" :background="false" layout="->,total,sizes, prev, pager, next" :total="total"
    @size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top: 20px;" />
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { safeRulesGroups } from '@/api/control/myServer';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CirclePlus } from '@element-plus/icons-vue'
import { delSafeRulesGroups, addSafeRulesGroupsOne, batchAddSafeRulesGroups } from '@/api/control/myServer'
import router from '@/router';

const route = useRoute();

const safeRulesList = ref<any>([]);//安全规则配置列表所有
const safeRulesListPage = ref<any>([]);//当前页的数据
const safeType = ref('ingress');//规则类型

const isRules = ref(false);//添加对话框开关

const addRulesList = ref<any>([{}]);//添加add表格
const rulesDetialOne = ref<any>({});//表格当前行未修改的数据

const protocolOptions = ref<any>([
  {
    value: '基本协议',
    label: '基本协议',
    children: [
      {
        value: '',
        label: '全部协议'
      },
      {
        value: 'tcp',
        label: '全部TCP'
      },
      {
        value: 'udp',
        label: '全部UDP'
      },
      {
        value: 'tcp1',
        label: '自定义TCP'
      },
      {
        value: 'udp1',
        label: '自定义UDP'
      },
    ]
  },
  {
    value: '常用协议端口',
    label: '常用协议端口',
    children: [
      {
        value: 'tcp 22',
        label: 'SSH(22)'
      },
      {
        value: 'tcp 23',
        label: 'Telnet(23)'
      },
      {
        value: 'tcp 80',
        label: 'HTTP(80)'
      },
      {
        value: 'tcp 443',
        label: 'HTTPS(443)'
      },
      {
        value: 'tcp 1433',
        label: 'MS SQL(1433)'
      },
      {
        value: 'tcp 1521',//不确定
        label: 'Oracle(1521)'
      },
      {
        value: 'tcp 3306',
        label: 'MySQL(3306)'
      },
      {
        value: 'tcp 3389',
        label: 'RDP(3389)'
      },
      {
        value: 'tcp 53',
        label: 'DNS(53/TCP)'
      },
      {
        value: 'udp 53',
        label: 'DNS(53/UDP)'
      },
      {
        value: 'tcp 20~21',
        label: 'FTP(20-21)'
      },
      {
        value: 'tcp 5432',
        label: 'PostgresQL(5432)'
      },
      {
        value: 'tcp 6379',
        label: 'Redis(6379)'
      },
      {
        value: 'tcp 389',
        label: 'LDAP(389)'
      },
      {
        value: 'tcp 8080',
        label: 'HTTP_ALT(8080)'
      },
      {
        value: 'tcp 27017',
        label: 'MongoDB(27017)'
      },
    ]
  },
]);//端口协议的级联选项

const typeShow = ref('IP地址');//源地址类型
const isAll = ref(false);//是否自定义端口
const protocolType = ref<any>([]);//协议类型选中的值

const currentPage = ref(1);//当前页数
const pageSize = ref(10);//每页条数
const total = ref(0);//总条数

onMounted(() => {
  getSafeRulesGroups();
});

//获取当前ip的类型
const getIPType = (e: any, index: number) => {
  typeShow.value = e;
  addRulesList.value[index].remote_ip_prefix = '0.0.0.0/0';
}

//分页切换每页条数
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getSafeRulesGroups();
}
//分页当前页数
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getSafeRulesGroups();
}

//切换规则类型
const chooseType = () => {
  getSafeRulesGroups();
}

//获取规则列表
const getSafeRulesGroups = () => {
  const data = {
    regionId: "",
    body: {
      limit: 10000,
      security_group_id: route.query.id
    }
  }
  safeRulesGroups(data).then((res: any) => {
    if (200 == res.code) {
      safeRulesList.value = res.data.security_group_rules.filter((item: any) => item.direction == safeType.value);
      total.value = safeRulesList?.value.length;
      safeRulesListPage.value = safeRulesList.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
    }
  })
};

//打开添加规则对话框
const addRules = () => {
  isRules.value = true;
};

//修改规则
const doUpdate = (row: any) => {
  row.isEdit = true;
  rulesDetialOne.value = JSON.parse(JSON.stringify(row));
};

//确认修改
const sureUpdate = async (row: any) => {
  row.protocol = row.protocol ? row.protocol[1] : '';
  //先删除原来的，添加进新的
  // const data = {
  //   "regionId": "",
  //   "body": {
  //     "security_group_rule_id": row.id
  //   }
  // }
  // let res = await delSafeRulesGroups(data);
  // if (200 == res.code) {
  //   //删除成功，新增一条
  //   addRulesMethod(row, '修改规则');
  //   row.isEdit = false;
  // }
};

//取消修改
const cancelUpdate = (row: any) => {
  for (let key in row) {
    if (rulesDetialOne.value[key]) {
      row[key] = rulesDetialOne.value[key]
    } else {
      row[key] = '';
    }
  }
  row.protocol = row.protocol ? row.protocol[1] : '';
  row.isEdit = false;
};

//端口协议改变
const ethertypeChange = (e: any, index: number) => {
  if ('基本协议' === e[0]) {
    if ('tcp' === e[1] || '' === e[1] || 'udp' === e[1]) {
      addRulesList.value[index].multiport = '1~65535';
      addRulesList.value[index].protocol = e[1];
      isAll.value = true;
    } else if ('tcp1' === e[1] || 'udp1' === e[1]) {
      addRulesList.value[index].multiport = null;
      addRulesList.value[index].protocol = e[1].substring(0, 3);
      isAll.value = false;
    }
  } else if ('常用协议端口' === e[0]) {
    const chooseValue = e[1].split(' ');
    isAll.value = true;
    addRulesList.value[index].multiport = chooseValue[1];
    addRulesList.value[index].protocol = chooseValue[0];
  }
};

//对话框表格复制一条规则
const pasteOne = (row: any, index: number) => {
  addRulesList.value.splice(index, 0, JSON.parse(JSON.stringify(row)));
};


//主页表格复制一条
const pasteOneTable = (row, index) => {
  ElMessageBox.confirm(
    `确定要复制这条安全组规则吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // addRulesMethod(row, '复制规则')
    })
    .catch(() => { })
};

//对话框删除一条规则
const delOne = (row, index) => {
  addRulesList.value.splice(index, 1);
};

//主页表格删除一条
const delOneTable = (row) => {
  ElMessageBox.confirm(
    `确定要删除这条安全组规则吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const data = {
        "regionId": "",
        "body": {
          "security_group_rule_id": row.id
        }
      }
      delSafeRulesGroups(data).then((res: any) => {
        if (200 == res.code) {
          getSafeRulesGroups();
          ElMessage.success('删除成功！')
        }
      })
    })
    .catch(() => { })
};

//弹窗新增一条规则
const addRulesOne = () => {
  addRulesList.value.push({});
};

/**
 * 新增规则方法
 * @param obj 添加，修改，复制的后的新数据
 * @param type 类型(添加，修改，复制)
 */
const addRulesMethod = (arr, type) => {
  //新增接口参数
  const data = {
    regionId: '',
    body: {
      security_group_id: route.query.id,
      body: {
        ignore_duplicate: false,
        security_group_rules: arr.map(item => {
          if (item.multiport === '1~65535'){
            item.multiport = null;
          }
          let itemData = <any>{
            direction: item.direction ? item.direction : null,
            description: item.description ? item.description : null,
            protocol: item.protocol ? item.protocol : null,
            action: item.action ? item.action : null,
            priority: item.priority ? item.priority : null,
            ethertype: item.ethertype ? item.ethertype : null,
            multiport: item.multiport ? item.multiport : null,
          }
          if (typeShow.value === 'IP地址') {
            itemData.remote_ip_prefix = item.remote_ip_prefix;
          } else if (typeShow.value === '安全组') {
            itemData.remote_group_id = item.remote_group_id;
          } else if (typeShow.value === 'IP地址组') {
            itemData.remote_address_group_id = item.remote_address_group_id;
          }
          return itemData;
        })
      }
    }
  };
  console.log(data, '批量添加参数');
  batchAddSafeRulesGroups(data).then((res: any) => {
    if (200 === res.code) {
      getSafeRulesGroups();
      isRules.value = false;
      ElMessage.success(`${type}成功！`)
    }
  })
}

//去掉对象空值的属性
const removeEmptyProperties = (obj) => {
  // 将对象转换为 [key, value] 数组
  const entries = Object.entries(obj);
  // 过滤掉属性值为空字符串的属性
  const filteredEntries = entries.filter(([key, value]) => value !== '');
  // 将过滤后的数组转换回对象
  const filteredObj = Object.fromEntries(filteredEntries);
  return filteredObj;
}

//确认新增表单
const sureAdd = () => {
  addRulesMethod(addRulesList.value, '添加规则');
};

//取消
const cancelAdd = () => {
  isRules.value = false;
  addRulesList.value = [{}];
};

//返回云服务器
const goback = () => {
  router.push("/control/myServer/cloudService");
}
</script>

<style scoped lang="less">
.page-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.con-title {
  width: 100%;
  height: 25px;
  display: flex;
  align-items: center;

  margin-bottom: 20px;

  span:nth-child(1) {
    display: flex;
    align-items: center;

    img {
      width: 14px;
      height: 14px;
    }
  }

  span:nth-child(2) {
    display: flex;
    align-items: center;
    margin-left: 10px;
    font-size: 16px;
  }
}

.table {
  margin-top: 20px;
}

.addbtn {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}
</style>
